import React, { useEffect, useState } from "react"
import { ISingleArticle } from "../../interface/Article"
import { formatTime } from "../../tools/publicFun"
import SideGuide from "../SideGuide"
import style from "./style.less"
import { NoAvatar, UnGood, UnSave, ReFresh, Loading } from "../../source/svgs"
import { ITab } from "../../interface/tab"
import { Button, Empty, Form, message, Modal, Tabs } from "antd"
import 'antd/dist/antd.css'
import { UserInfo } from "../../interface/account"
import { useNavigate } from "react-router-dom"
import TextArea from "antd/lib/input/TextArea"
import { addBug } from "../../service/bug"
import { INotice } from "../../interface/notice"
const { TabPane } = Tabs

interface IProps {
  hasMoreArticles: boolean
  notices: INotice[]
  hostInfo: UserInfo
  articleList: ISingleArticle[]
  getData: () => void
  init: () => void
  interrap: () => void
  setTab: (tab: ITab | undefined) => void
  setSort: (sort: ISortSelect) => void
}

interface ISort {
  lable: string
  value: string
}

type ISortSelect = 'time' | 'like' | 'save'

export default function MainContent(props: IProps) {
  const navigate = useNavigate()
  const colorArr: string[] = ['#e85724', '#afcd50', '#1195db', '#7e53e0', '#db639b', '#8a8a8a', '#6eb960', '#83c6c2', '#e9ac8b', '#d3a8b2']
  const [loading, setLoading] = useState<boolean>(false)
  const [showModal, setShowModal] = useState<boolean>(false)
  const sortItems: ISort[] = [
    {
      lable: "时间",
      value: "time"
    },
    {
      lable: "点赞量",
      value: "like"
    },
    {
      lable: "收藏量",
      value: "save"
    }
  ]

  useEffect(() => {
    if (props.articleList.length === 0) {
      setLoading(true)
    } else {
      setLoading(false)
    }
  }, [props])

  function handleArticleDetail(id: string) {
    navigate("/article/id=" + id)
  }

  async function handleAddBug(value: { content: string }) {
    // throw new Error("Function not implemented.")
    if (props.hostInfo.id !== '') {
      const data = await addBug({ content: value.content, userId: props.hostInfo.id })
      if (data.stat === 'ok') {
        message.success("提交成功，奖励猜猜是啥")
        setShowModal(false)
      } else {
        message.error(data.msg)
      }
    } else {
      message.info("请先登录，不然我咋知道是谁提交的bug")
    }
  }

  return (
    <React.Fragment>
      <div>
        <SideGuide changeTab={(tab: ITab | undefined) => { props.setTab(tab) }} />
        <div className={style.mainContent}>
          <div className={style.list} >
            <Tabs tabBarExtraContent={<div onClick={() => { props.init() }} className={style.freshBtn}><span>刷新数据</span><img src={loading ? Loading : ReFresh} alt="" /></div>} className={style.changeTab} defaultActiveKey={'time'} onChange={(value) => { props.setSort(value as ISortSelect) }}>
              {sortItems.map((item: ISort, index: number) => (
                <TabPane className={style.sortWord} tab={item.lable} key={item.value}>
                  {props.articleList.length === 0 ?
                    (<div className={style.empty}>
                      <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={false} />
                      <div>该板块还没有任何数据哦，<span onClick={() => { navigate("/create") }}>点击进行发布？</span></div>
                    </div>) :
                    props.articleList.map((article: ISingleArticle, index: number) => (
                      <div onClick={(e) => {  handleArticleDetail(article.id!) }} className={style.block} key={article.id!}>
                        <div className={style.titleBar}>
                          <div><span>{article.title!}</span></div>
                          <div className={style.goodSave}>
                            <div className={style.optionBlock}>
                              <img src={UnGood} alt="good" /><span className={style.number}>{article.like!.length}</span>
                            </div>
                            <div className={style.optionBlock}>
                              <img src={UnSave} alt="save" /><span className={style.number}>{article.save!.length}</span>
                            </div>
                          </div>
                        </div>
                        <div className={style.underInfo}>
                          <div className={style.authorInfo}>
                            <img className={style.avatar} src={article.author?.avatar! || NoAvatar} alt="" />
                            <div className={style.user}>
                              <div>{article.author?.nickname!}</div>
                              <div className={style.role}>{article?.author?.role! === "normal" ? "普通用户" : "管理员"}</div>
                              {(props.hostInfo.focus.findIndex(item => item === article.author?.id!) !== -1) ? (<div><span className={style.focus}>已关注</span></div>) : (<div></div>)}
                            </div>
                          </div>
                          <div className={style.tabs}>
                            {article.tabs.map((tab: ITab, index: number) => (
                              <div style={{ "backgroundColor": colorArr[Math.floor(Number((Math.random() * 10)))] }} className={style.tab} key={tab.value}>
                                <span>{tab.lable}</span>
                              </div>
                            ))}
                          </div>
                          <div>
                            <span className={style.publishTime}>{`发布于${formatTime(article.create_Ts, 'ONLY_DAY')}`}</span>
                          </div>
                        </div>
                        <div className={style.divide}></div>
                      </div>
                    ))}
                  {props.hasMoreArticles ? <div onClick={() => { props.getData() }} className={style.hasMore}>点击加载更多</div> : <div className={style.noMore}>没有更多了</div>}
                </TabPane>
              ))}
            </Tabs>
          </div>
          <div className={style.sider}>
            <div className={style.bugSubmmit}>
              <span onClick={() => { setShowModal(true) }}>提bug拿奖励</span>
            </div>
            <div className={style.noticePart}>
              {props.notices.length === 0 ? (
                <div className={style.empty}>
                  <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={false} />
                  <div>还没有任何公告</div>
                </div>
              ) :
                props.notices.map((notice: INotice, index: number) => (
                  <div className={style.noticeBlock} key={notice.create_Ts + index.toString()}>
                    <div className={style.noticeContent}>{notice.content}</div>
                    <div>{formatTime(notice.create_Ts, 'ONLY_DAY')}</div>
                  </div>
                ))
              }
            </div>
          </div>
        </div>
        <Modal destroyOnClose onCancel={() => { setShowModal(false) }} footer={null} className={style.reportWindow} visible={showModal}>
          <Form className={style.reportForm} onFinish={(value: { content: string }) => { handleAddBug(value) }}>
            <Form.Item label={"bug内容"} name={"content"}>
              <TextArea maxLength={200} />
            </Form.Item>
            <Form.Item>
              <Button htmlType={"submit"} type={"primary"}>提交</Button>
            </Form.Item>
          </Form>
        </Modal>
      </div>
    </React.Fragment>
  )
}

